/**
 * 
 */
package springdata_CrudRepository.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import springdata_CrudRepository.domain.User;
import springdata_CrudRepository.service.UserService;

/**
 * @author 罗老师【Long】
 * Version:1.0
 * 备注：本套课程提供全部源码+笔记+相关开发工具+答疑服务
 */
@Controller
public class UserController {
	
	@Resource
	private UserService userService;

	 @RequestMapping("/")
	 public String index() {
		 
		 return "index";
	 }
	 
	 //保存数据
	 @RequestMapping("/save")
	 public String save(User user) {
		 userService.add(user);
		 
		 return "forward:/list";
	 }
	 
	 
	 //查询所有的用户信息
	 @RequestMapping("/list")
	 public String list(Model model) {
		 
		 Iterable<User> users = userService.findAll();
		 model.addAttribute("users", users);
		 
		 return "list";
	 }
	 
	 //删除用户信息
	 @RequestMapping("/remove")
	 public String remove(Integer id) {
		
		 userService.delete(id);
		 
		 return "forward:/list";	
    }
	 
	 //根据用户id获取需要修改的用户的信息
	 @GetMapping("/update")
	 public String update(Model model,Integer id) {
		
		 User user = userService.findById(id);
		 model.addAttribute("user", user);
		 
		 return "modify";	
	}
	 
	 //修改用户信息
	 @PostMapping("/update")
	 public String executeUpdate(User user) {
		
		 userService.modify(user);
		 
		 return "forward:/list";		
	}
	 
	 //查询所有数据并进行排序
	 @RequestMapping("/sort")
	 public String sort(Model model) {
		 
		 Iterable<User> users = userService.findAllSort();
		 model.addAttribute("users", users);
		 
		 return "list";
	 }
	 
	 //进行分页查询
	 @RequestMapping("/pager")
	 public String pager(Model model,int pageIndex) {
		 
		Page<User> page = userService.findUserByPage(pageIndex);
		System.out.println("请求的第几页："+page.getNumber());
		System.out.println("当前页有多少个元素:"+page.getNumberOfElements());
		 System.out.println("总共有多少条数据:"+page.getTotalElements());
		 System.out.println("总页数："+page.getTotalPages());
		 
		 List<User> users = page.getContent();
		 model.addAttribute("users", users);
		 return "list";
	 }
}
